<?php
/*
 * Author  : top-songshijie
 * Email   : 997031758@qq.com
 * DateTime: 2023/03/24 18:10
 */

namespace SSJ\LaravelHelper\Services\Safe;

class SignService
{
    protected $key;

    public function __construct()
    {
        $this->key = config('laravel-helper.safe.sign_key');
    }

    /**
     * 生成签名（https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3）
     *
     * @param array $param
     *
     * @return string
     */
    public function makeSign($param)
    {
        ksort($param);
        $string = $this->toUrlParams($param);
        $string = $string . 'key=' . $this->key;
        $string = md5($string);

        return strtoupper($string);
    }

    /**
     * 验证签名
     *
     * @param array  $param
     * @param string $sign
     *
     * @return bool
     */
    public function verifySign($param, $sign)
    {
        $verify_sign = $this->makeSign($param);

        if ($verify_sign !== $sign) {
            return false;
        }

        return true;
    }

    /**
     * 格式化参数格式化成url参数
     *
     * @param array $param
     *
     * @return string
     */
    protected function toUrlParams($param)
    {
        $buff = '';
        foreach ($param as $k => $v) {
            if ($k != 'sign' && $v != '' && !is_array($v)) {
                $buff .= $k . '=' . $v . '&';
            }
        }

        return $buff;
    }
}